package com.swfgui.effects
{
	import com.swfgui.queue.MethodQueueElement;

	import flash.display.DisplayObject;
	import flash.geom.Point;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;

	public class Shake
	{
		public function Shake()
		{
		}

		private var isShake:Boolean = false;
		private var offset:uint = 4;
		private var speed:uint = 32;
		private var complete:MethodQueueElement = new MethodQueueElement(null);

		public function shake(dis:DisplayObject, times:uint = 2, args:Object=null):void
		{
			if (isShake)
			{
				return;
			}
			if (args)
			{
				complete.method = args.onComplete;
				complete.args = args.onCompleteParams;
				if (args.hasOwnProperty("offset"))
				{
					offset = args.offset;
				}
				if (args.hasOwnProperty("speed"))
				{
					speed = args.speed;
				}
			}

			isShake = true;
			var point:Point = new Point(dis.x, dis.y);
			var offsetXYArray:Array = [0,0];
			var num:int = 0;
			var u:int = setInterval(function():void 
				{
					offsetXYArray[num%2] = (num++)%4 < 2 ? 0:offset;
					if(num > (times*4 + 1))
					{
						clearInterval(u);
						num = 0;
						isShake = false;
						complete.call();
						complete.clear();
					}
					dis.x = offsetXYArray[0] + point.x;
					dis.y = offsetXYArray[1] + point.y;
				}, speed);
		}

		/**
		 * args:{offset:4, speed:32, onComplete:Function, onCompleteParams:Array}
		 * @param dis
		 * @param times
		 * @param args
		 */
		public static function shake(dis:DisplayObject, times:uint = 2, args:Object=null):void
		{
			var s:Shake = new Shake();
			s.shake(dis, times, args);
		}
	}
}